<template>
  <div class="pageBox">
    <head-component
      title="购物车"
      :back="false"
      :rightText="rightText"
      @onRightText="onRightText"
    ></head-component>
    <div class="noData flex-center" v-if="!list.length">
      <img class="noDataImg" src="../../image/cart/noData.png" alt="" />
      <div class="tips">亲，您的购物车还没有宝贝哦，快去添加吧~</div>
    </div>
    <div class="cart" v-else>
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <div class="list">
          <div class="listItem flex-row" v-for="item in list" :key="item.id">
            <div class="checkBox" @click="onCheckBox(item)">
              <img
                class="chooseImg"
                src="@/image/cart/weixuanzhong_btn.png"
                alt=""
                v-if="!item.status"
              />
              <img
                class="chooseImg"
                src="@/image/cart/xuanzhong.png"
                alt=""
                v-else
              />
            </div>

            <div class="right flex-between">
              <img class="rightImg" :src="item.thumb" alt="" />
              <div class="rightInfo flex-between">
                <div class="title flex">
                  <div class="kind">{{ item.genre == 0 ? "兑" : "报" }}</div>
                  <div class="goodsName">{{ item.goodsName }}</div>
                </div>
                <div class="skuBox flex-row" v-if="item.specTitle">
                  <div class="sku">{{ item.specTitle }}</div>
                </div>
                <div class="priceBox flex-between">
                  <div class="price">￥{{ item.price }}</div>
                  <van-stepper
                    v-model="item.num"
                    button-size="24px"
                    @plus="onPlus(item)"
                    @minus="onMinus(item)"
                    :disable-input="true"
                    @change="stepChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-list>

      <div class="tips2" v-if="!manage && disabled">
        不同品类商品不能同时结算
      </div>

      <div class="totalBox">
        <div class="totalCon flex-between">
          <div class="totalLeft flex-between">
            <div class="chooseAll flex-row" @click="onChooseAll">
              <img
                class="chooseAllImg"
                src="@/image/cart/weixuanzhong_btn.png"
                alt=""
                v-if="!chooseAllStatus"
              />
              <img
                class="chooseAllImg"
                src="@/image/cart/xuanzhong.png"
                alt=""
                v-else
              />
              <p>全选</p>
            </div>
            <div class="total flex-row" v-if="!manage">
              <div class="totalNum">
                共计{{ idList.length ? idList.length : 0 }}件，
              </div>
              <div class="totalTitle">合计：</div>
              <div class="totalPrice">￥{{ total }}</div>
            </div>
          </div>
          <button
            :class="[disabled ? 'totalBtn totalBtnGrey' : 'totalBtn']"
            :disabled="disabled"
            v-if="!manage"
            @click="settlement"
          >
            结算（{{ idList.length ? idList.length : 0 }}）
          </button>
          <button class="totalBtn" v-if="manage" @click="onDelete">删除</button>
        </div>
      </div>
    </div>
    <foot-component tab="3"></foot-component>
  </div>
</template>

<script type="text/ecmascript-6">
import { defineComponent, ref, watch } from "vue";
import headComponent from "../../components/headComponent.vue";
import footComponent from "../../components/footComponent.vue";
import { post } from "../../untils/request";
import { Toast } from "vant";
import router from "../../router";

export default defineComponent({
  components: {
    headComponent,
    footComponent,
  },
  setup() {
    const rightText = ref("管理"); // 右上角文本
    const manage = ref(false); // 控制结算删除显示

    const statusLength = ref(0); // 选中的购物车列表子元素个数

    const chooseAllStatus = ref(false); // 是否全选

    const disabled = ref(false);

    const page = ref(1);
    const lastId = ref(0);
    const loading = ref(true);
    const finished = ref(false);
    const list = ref([]); // 购物车列表

    const idList = ref([]); // 选中的购物车列表id
    const total = ref(0); // 选中的购物车列表总价
    const different = ref(0); // 判断不同品类商品不能同时结算 等于idList.length代表同种类商品

    //获取购物车列表
    function onLoad() {
      post("/portal/Shop", {
        module: "Cart",
        interface: "1005",
        data: {
          page: page.value,
          lastId: lastId.value,
        },
      }).then((res) => {
        chooseAllStatus.value = false;
        let datas = res.data.list;
        if (datas) {
          datas.forEach((item) => {
            item.status = false;
          });
          list.value = list.value.concat(datas);
          loading.value = false;
        }
        lastId.value = res.data.lastId;
        page.value = res.data.currentPage + 1;
        if (page.value > res.data.lastPage) {
          loading.value = false;
          finished.value = true;
        }
      });
    }
    onLoad();

    function onRightText() {
      if (!manage.value) {
        rightText.value = "完成";
        manage.value = !manage.value;
      } else {
        rightText.value = "管理";
        manage.value = !manage.value;
      }
    }

    //选择
    function onCheckBox(param) {
      list.value.forEach((item) => {
        if (item.id == param.id) {
          item.status = !item.status;
          if (item.status) {
            statusLength.value++;
            getIdList(item);
          } else {
            statusLength.value--;
            getIdList(item);
          }
        }
      });
    }

    // 得到选中的购物车列表id
    function getIdList(param) {
      if (param.status) {
        idList.value.push(param.id);
      } else {
        idList.value.splice(idList.value.indexOf(param.id), 1);
      }
    }

    // 监听选中的购物车列表子元素个数
    watch(statusLength, (newVal) => {
      if (newVal == list.value.length) {
        chooseAllStatus.value = true;
      } else {
        chooseAllStatus.value = false;
      }
    });

    // 监听选中的购物车列表id数组 计算合计,判断选择中的商品的类型是否相同
    watch(
      idList,
      (val) => {
        if (val.length > 1) {
          different.value = 0;
          total.value = 0;
          list.value.forEach((item) => {
            if (val.includes(item.id)) {
              total.value += item.price * item.num;
              if (item.genre == 0) {
                console.log("different.value++")
                different.value++;
              } else {
                console.log("different.value--")
                different.value--;
              }
            }
          });
        } else if (val.length == 1) {
          different.value = 0;
          total.value = 0;
          list.value.forEach((item) => {
            if (val.includes(item.id)) {
              total.value += item.price * item.num;
              different.value = 1;
            }
          });
        } else {
          total.value = 0;
          different.value = 0;
        }
        if (Math.abs(different.value) != val.length) {
          // 选择中的商品种类不同
          disabled.value = true;
          if (!manage.value) {
            Toast("不同品类商品不能同时结算");
          }
        } else {
          // 选择中的商品种类相同
          disabled.value = false;
        }
      },
      { deep: true }
    );

    // 全选
    function onChooseAll() {
      chooseAllStatus.value = !chooseAllStatus.value;
      if (chooseAllStatus.value) {
        list.value.forEach((item) => {
          item.status = true;
          statusLength.value = list.value.length;
        });
        idList.value = [];
        list.value.forEach((item) => {
          idList.value.push(item.id);
        });
      } else {
        list.value.forEach((item) => {
          item.status = false;
          statusLength.value = 0;
        });
        idList.value = [];
      }
    }

    // 步进器点击增加按钮时触发
    function onPlus(param) {
      list.value.forEach((item) => {
        if (item.id == param.id) {
          item.num++;
          changeNum(item);
        }
      });
    }

    // 步进器点击减少按钮时触发
    function onMinus(param) {
      list.value.forEach((item) => {
        if (item.id == param.id) {
          item.num--;
          changeNum(item);
        }
      });
    }

    // 步进器改变数量时触发  重新计算合计
    function stepChange() {
      console.log("步进器改变数量时触发");
      total.value = 0;
      list.value.forEach((item) => {
        if (idList.value.includes(item.id)) {
          total.value += item.price * item.num;
        }
      });
    }

    // 改变数量
    function changeNum(param) {
      post("/portal/Shop", {
        module: "Cart",
        interface: "1001",
        data: {
          id: param.id,
          num: param.num,
        },
      }).then(() => {
        // refresh();
      });
    }

    function refresh() {
      total.value = 0;
      idList.value = [];
      statusLength.value = 0;
      different.value = 0;
      page.value = 1;
      lastId.value = 0;
      loading.value = true;
      finished.value = false;
      list.value = [];
      onLoad();
    }

    //删除
    function onDelete() {
      if (idList.value.length == 0) {
        Toast("请选择商品");
        return;
      }
      post("/portal/Shop", {
        module: "Cart",
        interface: "1002",
        data: {
          id: idList.value,
        },
      }).then(() => {
        Toast("删除成功");
        refresh();
      });
    }

    //结算
    function settlement() {
      if (idList.value.length == 0) {
        Toast("请选择商品");
        return;
      }
      console.log("结算");
      router.push({
        path: "/cartSubmit",
        query: {
          idList: JSON.stringify(idList.value),
        },
      });
    }

    return {
      rightText,
      manage,
      chooseAllStatus,
      disabled,
      statusLength,
      page,
      lastId,
      list,
      loading,
      finished,
      idList,
      total,
      different,
      onLoad,
      onRightText,
      onCheckBox,
      onChooseAll,
      onPlus,
      onMinus,
      changeNum,
      refresh,
      settlement,
      getIdList,
      onDelete,
      stepChange,
    };
  },
});
</script>

<style scoped lang="less">
.pageBox {
  width: 100%;
  min-height: 100vh;
  padding-top: 88px;
  padding-bottom: 136px;
  background-color: #f5f5f5;
  :deep(.rightTitle) {
    color: #999999 !important;
  }
  .noData {
    flex-direction: column;
    padding-top: 100px;
    .noDataImg {
      width: 360px;
      height: 309px;
    }
    .tips {
      font-size: 26px;
      font-weight: 400;
      color: #999999;
      margin-top: 10px;
    }
  }
  .cart {
    .list {
      background-color: #fff;
      padding: 0 30px;
      .listItem {
        padding: 30px 0;
        height: 229px;
        border-bottom: 1px solid #f5f5f5;
        .checkBox {
          width: 40px;
          height: 40px;
          .chooseImg {
            width: 100%;
            height: 100%;
          }
        }
        .right {
          padding-left: 20px;
          height: 100%;
          width: 100%;
          .rightImg {
            width: 168px;
            height: 168px;
            border-radius: 10px;
          }
          .rightInfo {
            width: 100%;
            padding-left: 20px;
            flex-direction: column;
            align-items: flex-start;
            height: 100%;
            .title {
              .kind {
                font-size: 28px;
                font-weight: 500;
                color: #fa4b5a;
                margin-right: 20px;
                white-space: nowrap;
              }
              .goodsName {
                font-size: 28px;
                font-weight: 500;
                color: #333333;
              }
            }
            .skuBox {
              flex-wrap: wrap;
              .sku {
                font-size: 26px;
                font-weight: 400;
                color: #999999;
                margin-right: 28px;
              }
            }
            .priceBox {
              width: 100%;
              .price {
                font-size: 36px;
                font-weight: 500;
                color: #fa4b5a;
              }
            }
          }
        }
      }
    }
    .tips2 {
      margin-top: 51px;
      font-size: 26px;
      font-weight: 400;
      color: #e00b12;
      line-height: 37px;
      text-align: center;
    }
    .totalBox {
      width: 100%;
      height: 136px;
      background: #ffffff;
      box-shadow: 0px -1px 0px 0px #dadee6;
      position: fixed;
      left: 0;
      bottom: 88px;
      z-index: 1;
      .totalCon {
        width: 100%;
        height: 88px;
        .totalLeft {
          width: 100%;
          .chooseAll {
            padding-left: 30px;
            .chooseAllImg {
              width: 36px;
              height: 36px;
            }
            p {
              font-size: 26px;
              font-weight: 400;
              color: #999999;
              margin-left: 20px;
              white-space: nowrap;
            }
          }
          .total {
            width: 100%;
            justify-content: flex-end;
            padding-right: 20px;
            .totalNum {
              font-size: 24px;
              font-weight: 400;
              color: #999999;
            }
            .totalTitle {
              font-size: 26px;
              font-weight: 400;
              color: #333333;
            }
            .totalPrice {
              font-size: 30px;
              font-weight: 400;
              color: #e00b12;
            }
          }
        }
        .totalBtn {
          font-size: 28px;
          font-weight: 500;
          color: #ffffff;
          width: 220px;
          height: 88px;
          background: linear-gradient(270deg, #b30b11 0%, #f50811 100%);
          border: none;
        }
        .totalBtnGrey {
          background: #cccccc;
        }
      }
    }
  }
}
</style>